/*
 * @(#)ReflectionUtil.java  2012-6-7
 *
 * Copyright 2011-2011 Gopay Information and technology Co., Ltd.
 * Sanyunqiao, Chaoyang, Beijing, 100027, China.
 * All Rights Reserved.
 *
 * This software is the confidential and proprietary information of
 * Gopay Information and technology Co., Ltd. ("Confidential Information").
 * You shall not disclose such Confidential Information and shall use it only in
 * accordance with the terms of the license agreement you entered into with Gopay.
 */
package com.gopay.common.util;

import org.apache.commons.beanutils.BeanUtils;
import org.apache.commons.beanutils.ConvertUtils;
import org.apache.commons.beanutils.PropertyUtils;
import org.apache.commons.beanutils.converters.BigDecimalConverter;
import org.apache.commons.beanutils.converters.DateConverter;

/**
 * 反射工具类.
 * 
 */
public final class ReflectionUtil {

	/**
	 * 不同对象的属性拷贝
	 * 
	 * @param dest
	 * @param original
	 */
	public static Object copyProperties(Object dest, Object original) {
		if (null == dest || null == original) {
            return null;
        }
		try {
			ConvertUtils.register(new BigDecimalConverter(null), java.math.BigDecimal.class);
			ConvertUtils.register(new DateConverter(null), java.util.Date.class);
			
			//转换Timestamp  add by fanghw 20130321
			ConvertUtils.register(new DateConverter(null), java.sql.Timestamp.class);
			
			BeanUtils.copyProperties(dest, original);
		} catch (Exception e) {
			throw new RuntimeException(e);
		}
		return dest;
	}

	/**
	 * 获得source的name字段字符串值
	 * 
	 * @param source
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static String getProperty4String(Object source, String name) {
		try {
			Object value = PropertyUtils.getProperty(source, name);
			return value == null ? null : value.toString();
		} catch (Exception e) {
			throw new RuntimeException("系统异常：获取" + source.getClass().getName() + " 的字段" + name + "时出错", e);
		}
	}

	/**
	 * 获得source的name字段字符串值
	 * 
	 * @param source
	 * @param name
	 * @return
	 * @throws Exception
	 */
	public static void setProperty4String(Object source, String name, Object value) {
		try {
			PropertyUtils.setProperty(source, name, value);
		} catch (Exception e) {
			throw new RuntimeException("系统异常：设置" + source.getClass().getName() + " 的字段" + name + "时出错", e);
		}
	}
}
